﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using Microsoft.TeamFoundation.Client;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using System.Net;
using Microsoft.TeamFoundation;

namespace DatabaseSynchronizer {

    public static class Utils {


        private static string _encryptionKey = "7DA30D77-66F4-4A1F-A7C3-59CF645350F4";


        public static string EncryptString(string Message) {
            byte[] Results;

            UTF8Encoding UTF8 = new UTF8Encoding();
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(_encryptionKey));

            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            byte[] DataToEncrypt = UTF8.GetBytes(Message);

            try {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally {
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            return Convert.ToBase64String(Results);
        }


        public static string DecryptString(string Message) {
            byte[] Results;
            UTF8Encoding UTF8 = new UTF8Encoding();

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(_encryptionKey));

            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            byte[] DataToDecrypt = Convert.FromBase64String(Message);

            try {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally {
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            return UTF8.GetString(Results);
        }


        public static bool IsAlphanumeric(string value) {

            if (!string.IsNullOrEmpty(value)) {

                return Regex.IsMatch(value.Trim(), "^[0-9a-zA-Z ].+$");
            }
            else
                return false;
        }

        /// <summary>
        /// Checks for 5 or less digit number
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>

        public static bool IsValidPortNumber(string value) {

            bool valid = false;

            if (!string.IsNullOrEmpty(value)) {

                value = value.Trim();
                int port = 0;

                if (int.TryParse(value, out port)
                    && port.ToString() == value
                    && port != 0
                    && value.Length <= 5) {

                    valid = true;
                }
            }

            return valid;
        }

        /// <summary>
        /// Tries to connect to the TFS server and get the nodes collection
        /// </summary>
        /// <param name="url">Required</param>
        /// <param name="credentialsProvider">Pass null to use VS cache credentials</param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public static ConnectionResult IsValidTfsUrl(string url, NetworkCredential networkCredentials, out string errorMessage) {

            errorMessage = "Invalid URL.";

            if (string.IsNullOrEmpty(url)) return ConnectionResult.Failure;

            Uri tfsUri = new Uri(url);

            TfsTeamProjectCollection tfsServer;

            if (networkCredentials == null) {
                tfsServer = new TfsTeamProjectCollection(tfsUri);
            }
            else {
                tfsServer = new TfsTeamProjectCollection(tfsUri, CredentialFactory.CreateCredentials(networkCredentials));
            }

            try {
                tfsServer.Authenticate();
            }
            catch (TeamFoundationServerUnauthorizedException ex) {
                errorMessage = ex.Message;
                return ConnectionResult.InvalidCredentials;
            }
            catch (Exception ex) {
                errorMessage = ex.Message;
                return ConnectionResult.Failure;
            }

            return ConnectionResult.Success;
        }

    }
}